//
//  WYMainTabBarVC.m
//  TabBar主界面框架
//
//  Created by 王琰 on 14-11-21.
//  Copyright (c) 2014年 王琰. All rights reserved.
//

#import "WYMainTabBarVC.h"
#import "JSBadgeView.h"
#import "MFSideMenu.h"
#import "AllGoosVC.h"
#import "WYBtn.h"
#import "QiDongVC.h"
#import "WYBase64Fun.h"
//激活统计
#define JIHUO_URL @"activation"
//首次启动图
#define QIDONG_PIC_URL @"/api/ApiMisc/getAppStartup"
//主界面单例
static WYMainTabBarVC *mainTVC = nil;
@interface WYMainTabBarVC ()
{
    /*********默认五个按钮***********/
    //1,按钮1
    WYBtn *_oneBtn;
    //3，按钮3
    WYBtn *_threeBtn;
    //4,按钮4
    WYBtn *_fourBtn;
    //5,按钮5
    WYBtn *_fiveBtn;
    //存放按钮的数组
    NSArray *_btns;
    //圆角通知
    JSBadgeView *badgeView;
    //圆角通知的背景
    UIView *whitbadBg;
    //首次标志
    BOOL _firstFlag;
}
@end

@implementation WYMainTabBarVC


- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}
/**************
 *获取主界面单例
 ****************/
+ (WYMainTabBarVC *)shareMainTaBarVC
{
    static WYMainTabBarVC *mainTVC  = nil;
    static dispatch_once_t once;
    dispatch_once(&once, ^{
        mainTVC = [[WYMainTabBarVC alloc]init];
    });
  return mainTVC;
}
- (instancetype)init
{
    if (self = [super init]) {
        
    }
    return self;
}


- (void)viewDidLoad
{
    [super viewDidLoad];
    //加载自定义的tabbar
    [self loadCustomTabBar];
    
    __block WYMainTabBarVC* bself = self;
    double delayInSeconds = 10.0;
    dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(delayInSeconds * NSEC_PER_SEC));
    dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
        //加载首次启动图片
        [bself requestForQiDongPic];
    });
    
    
}
/************
 *请求首次启动加载图
 ***************/
- (void)requestForQiDongPic
{
    
    [WYRequest startPostForDicWithUrlStR:[NSString stringWithFormat:@"%@%@",DBB_IP,QIDONG_PIC_URL] Parameters:nil successBlock:^(NSDictionary *dic) {
        NSNumber *ret = dic[@"ret"];
        if ([ret intValue] == 0) {
            NSArray *pics = dic[@"data"];
            if (pics.count>0) {
                //获取图片开关
                NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
                [user setObject:[WYPublic getUsefullStr:pics[0][@"is_show"]] forKey:@"qidong_pic_flag"];
                [user synchronize];
                
                NSString *imgPath = [WYPublic getUsefullStr:pics[0][@"img_url"]];
                if (imgPath.length>0) {
                    [self updataImg:imgPath];
                }
            }
        }
    } failedBlock:^{
        
    } needLog:NO];
}
//下载图片
- (void)updataImg:(NSString *)imgPath
{
    /**************下载图片*************/
    SDWebImageManager *manager = [SDWebImageManager sharedManager];
    [manager downloadImageWithURL:[NSURL URLWithString:imgPath] options:SDWebImageRetryFailed progress:^(NSInteger receivedSize, NSInteger expectedSize) {
        
    } completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, BOOL finished, NSURL *imageURL) {
        //先保存图片到本地
        NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES);
        NSString *filePath = [[paths objectAtIndex:0] stringByAppendingPathComponent:@"qidong_pic.jpg"];   // 保存文件的名称
        NSData *imageData = UIImageJPEGRepresentation([UIImage imageWithCGImage:image.CGImage], 1.0);
        [imageData writeToFile:filePath atomically:YES];
    }];

}
/************
 *定制tabbar
 ***************/
- (void)loadCustomTabBar
{
    //隐藏系统tabbar
    self.tabBar.hidden = YES;
    //初始化自定义的tabbar
    self.customTabBar = [[UIView alloc] initWithFrame:CGRectMake(0, self.view.frame.size.height - 49, self.view.frame.size.width, 49)];
    self.customTabBar.backgroundColor = [UIColor whiteColor];
    //定制tabBar
    [self creatCustomTabBar];
    [self.view addSubview:self.customTabBar];
}

/**
 *定制tabBar
 **************/
- (void)creatCustomTabBar
{
    //分割线
    [self.customTabBar addSubview:[WYPublic getFenGexian:0 :0 :WYMWITH :0.5]];
    
    //背景图片
    UIImageView *bgImg = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 40)];
    bgImg.image = [UIImage imageNamed:@"tabbar-bg"];
    NSInteger num = 3;
    NSString *show_shopping = [[NSUserDefaults standardUserDefaults] valueForKey:@"show_shopping"];
    if (show_shopping.integerValue == 1) {
        num = 4;
    }
    //五个界面关联的按钮
    //定义按钮的长和宽
    CGFloat btnHeight = 49;
    //1,按钮1
    CGFloat btnWidth = WYMWITH/num;
    
    _oneBtn = [[WYBtn alloc]initWithFrame:CGRectMake(0, 0, btnWidth, btnHeight) AndImgNom:[UIImage imageNamed:@"icon_menu_home_normal"] AndImgPress:[UIImage imageNamed:@"icon_menu_home_press"] AndTitle:@"夺宝吧"];
    _oneBtn.sel_flag = YES;
    //3，按钮3
    _threeBtn = [[WYBtn alloc]initWithFrame:CGRectMake(btnWidth, 0, btnWidth, btnHeight) AndImgNom:[UIImage imageNamed:@"icon_menu_jiexiao_normal"] AndImgPress:[UIImage imageNamed:@"icon_menu_jiexiao_press"] AndTitle:@"最新揭晓"];
    //4,按钮4
    _fourBtn = [[WYBtn alloc]initWithFrame:CGRectMake(btnWidth*2, 0, btnWidth, btnHeight) AndImgNom:[UIImage imageNamed:@"icon_menu_buy_normal"] AndImgPress:[UIImage imageNamed:@"icon_menu_buy_press"] AndTitle:@"购物车"];
    //5,按钮5
    _fiveBtn = [[WYBtn alloc]initWithFrame:CGRectMake(btnWidth*(num-1), 0, btnWidth, btnHeight) AndImgNom:[UIImage imageNamed:@"icon_menu_me_normal"] AndImgPress:[UIImage imageNamed:@"icon_menu_me_press"] AndTitle:@"我的夺宝"];
    //添加圆角通知
    UIImageView *iv = [_fourBtn getImgView] ;
    whitbadBg = [[UIView alloc]initWithFrame:CGRectMake(iv.frame.size.width - 11, 0, 15, 15)];
    whitbadBg.backgroundColor = [UIColor whiteColor];
    whitbadBg.layer.cornerRadius = whitbadBg.frame.size.width/2;
    [iv addSubview:whitbadBg];
    badgeView = [[JSBadgeView alloc] initWithParentView:[_fourBtn getImgView] alignment:JSBadgeViewAlignmentTopRight];
    badgeView.hidden = YES;
    whitbadBg.hidden = YES;
    [self updateCountToCar];
    //初始化按钮数组
    _btns = @[_oneBtn,_threeBtn,_fiveBtn];

    if (show_shopping.integerValue == 1) {
        _btns = @[_oneBtn,_threeBtn,_fourBtn,_fiveBtn];
    }

    
    //给所有按钮设置tag和监听事件
    for (NSInteger i = 0; i < _btns.count; i++) {
        WYBtn *btn = _btns[i];
        btn.tag = i + 1;
        [btn addTarget:self action:@selector(btnsOnClick:) forControlEvents:UIControlEventTouchUpInside];
        //将按钮添加到customTabBar上
        [self.customTabBar addSubview:btn];
    }
    

    //设置默认的被选中的按钮
    _oneBtn.selected = YES;
    
}
/**
 *给TabBar按钮设置监听事件
 ********/
- (void)btnsOnClick:(WYBtn *)btn
{
//    if (btn.tag == _btns.count) {
//        if ([WYPublic ifUserHaveLogin] == NO || [UserInfo isUserInfoExist] == NO) {
//            return;
//        }
//    }
        //先将所有的按钮选中状态至为no
        for (WYBtn *bbt in _btns) {
            bbt.sel_flag = NO;
        }

        //再将当前按钮的选中状态至为yes
        btn.sel_flag = YES;
        //改变当前界面
        self.selectedIndex = btn.tag - 1;
    
}
//tabBar的
- (void)tabBarHiddenOrNot
{
    self.customTabBar.hidden = !self.customTabBar.hidden;
}
- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

//获取购物车按钮 用于加入购物车动画
- (UIView *)getShoppingCarBtn
{
    return _fourBtn;
}
//购物车按钮个数提示刷新
- (void)updateCountToCar
{
    NSArray *car = [[WYDataBase sharedDataBase]getAllpdcInCar];
    badgeView.badgeText = [NSString stringWithFormat:@"%ld",(unsigned long)car.count];
    if (car.count == 0) {
        badgeView.hidden = YES;
        whitbadBg.hidden = YES;
    }else{
        badgeView.hidden = NO;
        whitbadBg.hidden = NO;
    }
}

//搜索商品按钮点击后，改变TabBar 及menu结构的方法
- (void)seachBtnOnClick:(NSString *)text
{
    AllGoosVC *allvc = [[AllGoosVC alloc]init];
    allvc.seach_word = text;
    [allvc reloadVCWithSeachText:text];
    [[WYMainTabBarVC shareMainTaBarVC].navigationController pushViewController:allvc animated:NO];
    [self.menuContainerViewController setMenuState:MFSideMenuStateClosed completion:^{
    }];
}
//登录成功后调用
- (void)changeSelectedWithIndex:(NSInteger)index
{
    self.selectedIndex = index;
    //先将所有的按钮选中状态至为no
    for (WYBtn *bbt in _btns) {
        bbt.sel_flag = NO;
    }
    WYBtn *bbt = _btns[index];
    bbt.sel_flag = YES;
}
@end
